﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace HuiZe.education.View.Ethan
{
    /// <summary>
    /// PART_Media_Image_List_.xaml 的交互逻辑
    /// </summary>
    public partial class PART_Media_Image_List : Grid
    {
        public PART_Media_Image_List()
        {
            InitializeComponent();
            _ShowImage1Animation = (Storyboard)this.FindResource("ShowImage1Animation");
            _ShowImage2Animation = (Storyboard)this.FindResource("ShowImage2Animation");
        }

        public void SetImageList(string[] _images)
        {
            _index = 0;
            _list_image = _images;
            _dic_bmp = new Dictionary<string, BitmapImage>();
        }

        public void MoveNext()
        {
            if (_index == _list_image.Length)
                _index = 0;

            string _path = _list_image[_index];
            if (!_dic_bmp.ContainsKey(_path))
            {
                BitmapImage _bmp = new BitmapImage();
                _bmp.CacheOption = BitmapCacheOption.OnLoad;
                _bmp.BeginInit();
                _bmp.StreamSource = new MemoryStream(GetFileData(_path));
                _bmp.EndInit();
                _bmp.Freeze();

                _dic_bmp.Add(_path, _bmp);
            }
            if (_index % 2 == 0)
            {
                PART_Image1.Source = _dic_bmp[_path];
                _ShowImage1Animation.Begin();
            }
            else
            {
                PART_Image2.Source = _dic_bmp[_path];
                _ShowImage2Animation.Begin();
            }

            _index++;
        }

        byte[] GetFileData(string _path)
        {
            byte[] _buffers = null;
            using (var _fs = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                _buffers = new byte[_fs.Length];
                _fs.Read(_buffers, 0, _buffers.Length);
                _fs.Close();
            }
            return _buffers;
        }

        int _index;
        string[] _list_image;
        Dictionary<string, BitmapImage> _dic_bmp;
        Storyboard _ShowImage1Animation;
        Storyboard _ShowImage2Animation;
    }
}
